
float4 LightColor;
float Shininess;
float SpecularPower;
float4 AmbientLightColor;

texture2D NormalMap;
sampler2D NormalMapSampler = sampler_state
{
    Texture = <NormalMap>;
    MinFilter = linear;
    MagFilter = linear;
    MipFilter = linear;
};

texture2D Texture;
sampler2D DiffuseTextureSampler = sampler_state
{
    Texture = <Texture>;
    MinFilter = linear;
    MagFilter = linear;
    MipFilter = linear;
};

struct VS_OUTPUT
{
    float4 position : POSITION0;
    float2 texCoord : TEXCOORD0;
    float3 posToLight : TEXCOORD1;
    float3 posToEye : TEXCOORD2;
    float3x3 tangentToWorld    : TEXCOORD3;
};

float4 main( VS_OUTPUT input ) : COLOR0
{
    
    // look up the normal from the normal map, and transform from tangent space
    // into world space using the matrix created above.  normalize the result
    // in case the matrix contains scaling.
    float3 normalFromMap = tex2D(NormalMapSampler, input.texCoord);
    normalFromMap = mul(normalFromMap, input.tangentToWorld);
    normalFromMap = normalize(normalFromMap);
    
    // clean up our inputs a bit
    input.posToEye = normalize(input.posToEye);
    input.posToLight = normalize(input.posToLight);    
    
    // use the normal we looked up to do phong diffuse style lighting.    
    float nDotL = max(dot(normalFromMap, input.posToLight), 0);
    float4 diffuse = LightColor * nDotL;
   
    float3 halfEyeLight = 0.5 * (input.posToLight + input.posToEye); 
    
    float4 specular = Shininess * LightColor * pow(max(dot(halfEyeLight, normalFromMap),0), SpecularPower);
    
    float4 diffuseTexture = tex2D(DiffuseTextureSampler, input.texCoord);
    
    // return the combined result.
    return (diffuse + AmbientLightColor) * diffuseTexture + specular;
}